package com.kpmg.datalake.schedule.service.impl;

import com.kpmg.datalake.schedule.model.ScheduleJob;
import com.kpmg.datalake.schedule.model.ScheduleJobLog;
import com.kpmg.datalake.schedule.utils.TaskUtils;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.Job;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;

/**
 * description: 若一个方法一次执行不完下次轮转时则等待改方法执行完后才执行下一次操作
 * 非并发执行
 *
 * @author zhaohp
 */
@DisallowConcurrentExecution
public class QuartzJobFactoryDisallowConcurrentExecution implements Job {

    @Override
    public void execute(JobExecutionContext context) {
        long beginTime = System.currentTimeMillis();
        boolean isError = false;
        ScheduleJob scheduleJob = null;
        ScheduleJobLog scheduleJobLog = new ScheduleJobLog();
        Exception error = null;
        try {
            scheduleJob = (ScheduleJob) context.getMergedJobDataMap().get(TaskUtils.SCHEDULE_JOB);
            if (scheduleJob == null) {
                scheduleJob = new ScheduleJob();
                JobDetail jobDetail = context.getJobDetail();
                scheduleJob.setJobAction(jobDetail.getJobClass().getName());
                scheduleJob.setJobName(jobDetail.getKey().getName());
                scheduleJob.setJobGroup(jobDetail.getKey().getGroup());
                scheduleJob.setJobDesc(jobDetail.getDescription());
            }
            scheduleJob.setNextTime(context.getNextFireTime());
            //记录job 日志
            scheduleJobLog = TaskUtils.insertScheduleLog(scheduleJob, beginTime);
            //执行job 信息
            TaskUtils.invokeMethod(scheduleJob);
        } catch (Exception e) {
            error = e;
            isError = true;
        } finally {
            //跟新job处理情况
            TaskUtils.updateScheduleLog(scheduleJob, scheduleJobLog, isError, error);
        }
    }
}